/*=========================================================================

     human.cpp  -  Copyright (C) 1993-2005 by Don Cross

     Contains the class HumanChessPlayer.

=========================================================================*/

#include "chess.h"


HumanChessPlayer::HumanChessPlayer ( ChessUI &ui ):
    ChessPlayer(ui),
    automaticSingularMove (false)
{
}


HumanChessPlayer::~HumanChessPlayer()
{
}


bool HumanChessPlayer::GetMove ( 
    ChessBoard &board,
    Move       &move,
    INT32      &timeSpent )
{
    MoveList legalMoves;
    int      i;
    int      source, dest;
    INT32    startTime = ChessTime();

    board.GenMoves ( legalMoves );
    if ( legalMoves.num==1 && automaticSingularMove )
    {
        userInterface.NotifyUser ( 
            "You have only one legal move - it will be made for you." );

        userInterface.DisplayMove ( board, move = legalMoves.m[0] );
        timeSpent = 0;
        return true;
    }

    for(;;)     // keep looping until UI returns a legal move
    {
        SQUARE promIndex = 0;
        if ( !userInterface.ReadMove ( board, source, dest, promIndex ) )
        {
            timeSpent = ChessTime() - startTime;
            return false;
        }

        // Regenerate legal moves in case they edited the board.
        board.GenMoves ( legalMoves );

        // The following check allows certain UI tricks to work...
        if ( dest == SPECIAL_MOVE_NULL ||
           (dest & SPECIAL_MOVE_MASK) == SPECIAL_MOVE_EDIT )
        {
            move.source = source;
            move.dest = dest;
            move.score = 0;
            timeSpent = ChessTime() - startTime;
            return true;
        }

        // This checks for pawn promotion and stuff like that.
        move.Fix ( board, source, dest, promIndex, userInterface );

        // See if the move we just read is legal!
        for ( i=0; i < legalMoves.num; i++ )
        {
            if ( move == legalMoves.m[i] )
            {
                // We found the move in the list of legal moves.
                // Therefore, the move must be legal.
                timeSpent = ChessTime() - startTime;
                return true;
            }
        }
    }
}
